package indi.gao.file.web;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author :gaolei
 * @version :v1.0
 * @projectName :GLUtil
 * @description :
 * @createDate :2022/4/5 4:24 下午
 */
public class DingUtil {

    /**
     * 发送钉钉群消息
     *
     * @param message
     */
    public static void sendMessage(String message) {
        String accessToken = "ddbdfbe1eb0d7b26b85ca6d301f44749e0e834e12967e26bfe2e63cc5affe5ed";
        String secret = "SECf17c42f667b25f558d00e170f42790bdd7b7f896e2882542c81b9c6e3781756e";

        //计算签名
        try {
            Long timestamp = System.currentTimeMillis();
            String sign = sign(secret, timestamp);
            String data = "{\"msgtype\":\"text\",\"text\":{\"content\":\"" + message + "\"}}";
            HttpUtil.post("https://oapi.dingtalk.com/robot/send?access_token=" + accessToken + "&timestamp=" + timestamp + "&sign=" + sign, data);
        } catch (Exception e) {
            System.out.println("钉钉告警消息发送失败 内容：{} 错误 信息{}"+JSONObject.toJSONString(message));
        }

    }

    private static String sign(String secret, Long timestamp) throws Exception {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        String sign = Base64.encode(signData);
//        String sign = URLEncoder.encode(new String(com.alibaba.nacos.client.identify.Base64.encodeBase64(signData)), "UTF-8");
        return sign;
    }
}
